package sz.szsmk.citizencard.retrofitrxjava.newversion

import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import rx.schedulers.Schedulers
import sz.szsmk.citizencard.retrofitrxjava.newversion.interceptor.HeadParamInterceptor
import sz.szsmk.citizencard.util.Constant
import java.net.CookieManager
import java.util.concurrent.TimeUnit

/**
 *  author : hyt
 *  date : 2020/5/8
 *  description :
 */
object HttpDateSource {

    private val TIMEOUT_READ = 120
    private val TIMEOUT_CONNECTION = 30

      fun getOkHttpClient(): OkHttpClient? {
        val httpLoggingInterceptor = HttpLoggingInterceptor { message ->
            Log.e("--->>", message)
        }
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        return OkHttpClient.Builder()
                .connectTimeout(TIMEOUT_CONNECTION.toLong(), TimeUnit.SECONDS)
//                .addInterceptor(GetInterceptor())
//                .addInterceptor(PostInterceptor())
                //头部数据
                .addInterceptor(HeadParamInterceptor())
                .addNetworkInterceptor(httpLoggingInterceptor)
                .readTimeout(TIMEOUT_READ.toLong(), TimeUnit.SECONDS)
                .writeTimeout(TIMEOUT_READ.toLong(), TimeUnit.SECONDS)
                .dns(ApiDns())
                .build()
    }

    var retrofitMap = mutableMapOf<String, Any>()

    //保证 一个域名的请求 是一个retrofit 对象
    fun <T> createApi(clazz: Class<T>?, url: String?): T? {
        if(!retrofitMap.contains(url)){
            val retrofit = Retrofit.Builder()
                    .baseUrl(url)
                    .client(getOkHttpClient())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io()))
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
            url?.let {
                retrofitMap.put(it, retrofit.create(clazz)!!)
            }
        }
        return retrofitMap[url] as T
    }

    fun createApi() = createApi(NewHttpApi::class.java, Constant.BASE_URL)
    fun createApigfh() = createApi(NewHttpApi::class.java, Constant.GHFUL)

}